﻿
Partial Class App_UserAccounts
    Inherits MyUI.PageBaseApp

#Region "PAGE"
    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load


        If Not Me.IsPostBack Then

            SetListAccount()
            SocialAccount()
            SetDataSubscription()
        End If

        If CurrUser IsNot Nothing Then
            Me.PnlSocialAcc.Visible = CurrUser.Id = 1 Or CurrUser.Id = 2
        End If

        Exit Sub
        Dim nodes As New List(Of Object)
        Dim edges As New List(Of Object)
        Dim CurrAccount = CurrUser.CurrAccount
        Dim accs = CurrAccount.Tab_Message_Post.
            REL.Message_Post.Account.
            GroupBy("account_id").
            SetSelect("account.*,count(*) as count").
            OrderBy("count(*) desc").
            Limit(20).
        ToDataTable

        nodes.Add(New With {.id = CurrAccount.Id, .label = CurrAccount.Fullname, .image = CurrAccount.Avatar, .value = 2, .shape = "circularImage"})

        Dim accdirect = (From dr In accs.Rows).ToDictionary(Of String, String)(Function(o) ("@" & o("username")).ToString, Function(o) o("id"))
        'accdirect.Add("@" & CurrAccount.Username, CurrAccount.Id)

        For Each acc In accs.Rows
            If CurrAccount.Id <> acc("Id") Then
                nodes.Add(New With {.id = acc("Id"), .label = acc("Fullname"), .image = acc("Avatar"), .title = acc("description"), .value = 1, .shape = "circularImage"})
                edges.Add(New With {.from = CurrAccount.Id, .to = acc("Id"), .value = acc("count"), .label = acc("count")})


                Dim a = DB.TAB.Account.GetByPK(acc("id"))
                Dim posts = a._Tab_Account_Post.Where("post_text", "REGEXP", "@.+").ToList
                Dim menz As New Dictionary(Of String, Integer)
                For Each p In posts
                    Dim res = Regex.Matches(p.Post_Text, "@\w+")

                    For Each r In res
                        If Not menz.ContainsKey(r.value) Then
                            menz.Add(r.value, 0)
                        End If
                        menz(r.value) += 1
                    Next
                Next

                Dim menznode = (From m In menz Order By m.Value Descending Take 10).ToList
                For Each m In menznode
                    nodes.Add(New With {.id = acc("Id") & m.Key, .label = m.Key, .shape = "box"})
                    If accdirect.ContainsKey(m.Key) Then
                        edges.Add(New With {.from = acc("Id"), .to = accdirect.ContainsKey(m.Key), .value = m.Value, .label = m.Value})
                    Else
                        edges.Add(New With {.from = acc("Id"), .to = acc("Id") & m.Key, .value = m.Value, .label = m.Value})

                    End If
                Next

            End If
        Next




        Dim json = MyApp.JSONSerialize(New With {
            .nodes = nodes, .edges = edges
        })

        Me.AddJScript(SF("draw({0});", json))

    End Sub

#End Region

#Region "SOCIAL ACCOUNT"

    Protected Sub SetListAccount()
        Dim List = Me.ListAccount


        Dim dt = DB.TAB.Account.
            REL.Account.User_Account.
            REL.Account.Account_Add_Info.
            REL.Account.Account_Auth.
            BY.User_Account.User_Id(CurrUser.Id).
            Where("disabled", "<", 2).
        ToDataTable()

        UI.ListData.Bind(List, dt, {"account_id"})

        Me.JsVar("limitaccount") = MyApp.GetUserLimitPlan(GloukDB.Plan.LimitType.ACCOUNT_PER_USER, False)

        Me.UpdAccount.Update()

    End Sub

    Protected Sub ListAccount_ItemCommand(sender As Object, e As ListViewCommandEventArgs) Handles ListAccount.ItemCommand
        Dim List As ListView = sender
        Dim Row = UI.ListDataItem.GetRow(e.CommandSource)

        If Row IsNot Nothing Then

            Dim id = UI.ListDataItem.GetKey(e.CommandSource)
            Dim accauth = DB.TAB.Account_Auth.GetByPK(id)

            Select Case e.CommandName
                Case "ADD_ANALISYS"


                    If Not MyApp.GetUserLimitPlan(GloukDB.Plan.LimitType.FOLLOWER_ANALYSIS_PER_USER, True, accauth.Account_Id) Then

                        accauth.Analysis_Followers = True

                    Else

                        If CurrUser.View_EnabledAccount.Where("Analysis_Followers", "=", True).ToList.Count = 0 Then

                            accauth.Analysis_Followers = True
                            accauth.Analysis_Followers_Limit = CurrUser.Plan.Follower_Analysis_Per_User

                        End If
                    End If

                    DB.SubmitChanges()
                    Me.SetListAccount()


                Case "REMOVE_ANALISYS"
                    accauth.Analysis_Followers = False
                    accauth.Analysis_Followers_Limit = 0
                    DB.SubmitChanges()
                    SetListAccount()

                Case "DELETE_ACCOUNT"

                    Dim useracc = CurrUser.Tab_User_Account(accauth.Account_Id).ToObj
                    DB.DeleteOnSubmit(useracc)
                    DB.SubmitChanges()

                    'Response.Redirect("/#USERACCOUNT")
                    'UI.Page.RedirectTopJS("/#USERACCOUNT")
                    Me.AddJScript("top.location.reload();")

                    'SetListAccount()



            End Select

        End If



    End Sub

    Private Sub SocialAccount()

        Dim Network = UI.Page.GetValue("network")


        If Network = "paypal" Then

            Dim UrlRedir = Me.Request.Url.Scheme & "://" & Me.Request.Url.Host & Me.Request.Url.AbsolutePath & "?network=" & Network

            If Request("token") <> "" Then
                'Me.BtnPayPalConfirm.Visible = True
                Exit Sub
            Else

                Dim Uri As New UriBuilder("https://api-3t.sandbox.paypal.com/nvp")

                Dim queryString = HttpUtility.ParseQueryString("")

                queryString.Add("USER", "evolvo.net-facilitator_api1.gmail.com")
                queryString.Add("PWD", "1391768464")
                queryString.Add("SIGNATURE", "A2qv3pr765jIRYPhGsApwatsI0jTA.Ae-WRnVV3h7TRIcux9M09ARmA3")

                queryString.Add("VERSION", "93")
                queryString.Add("METHOD", "SetExpressCheckout")
                queryString.Add("PAYMENTREQUEST_0_PAYMENTACTION", "SALE")
                queryString.Add("PAYMENTREQUEST_0_AMT", "10")
                queryString.Add("PAYMENTREQUEST_0_CURRENCYCODE", "USD")
                queryString.Add("PAYMENTREQUEST_0_DESC", "Abbonamento mensile")
                '
                queryString.Add("RETURNURL", UrlRedir)
                queryString.Add("CANCELURL", "http://www.evolvonet.it")

                Uri.Query = queryString.ToString '& "&q=" & webClient.UrlEncode(q)

                Dim ww As New Net.WebClient
                Dim Res = ww.DownloadString(Uri.Uri.AbsoluteUri)


                Dim rerq = HttpUtility.ParseQueryString(Res)

                Dim token = rerq("TOKEN")
                'Dim o = MyApp.JSONDeserialize(Res)

                'Me.AddJScript(SF("paypal('{0}');", token))

                Response.Redirect("https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=" & token)

            End If

        End If

        If Network <> "" Then

            Dim UrlRedir = Me.Request.Url.Scheme & "://" & Me.Request.Url.Host & Me.Request.Url.AbsolutePath & "?network=" & Network

            Dim net = MyApp.EnumVal(Of WebApi.Type)(Network)

            Select Case net
                Case WebApi.Type.TWITTER

                    'Dim oauth As WebApi.Oauth.Oauth = New WebApi.Oauth.Oauth With {
                    '    .oauthConsumerSecret = "kLgJlMmE0iWToUUK3xF15K8f9dwYjYjJRHg3o7Zw",
                    '    .oauthConsumerKey = "N89RIjsDiPGuqzHDMteSQ",
                    '    .oauthCallback = UrlRedir
                    '}

                    Dim oauth As WebApi.Oauth.Oauth = New WebApi.Oauth.Oauth With {
                        .oauthConsumerSecret = "JIwiOoxJRuqOep0kMZMb9a590KmePUjUMxhhyB1CXmTOs3lTWQ",
                        .oauthConsumerKey = "ZKKBh0wOGlPf0ukmAKEedbiU7",
                        .oauthCallback = UrlRedir
                    }

                    Dim tw = New MyApp.Network.Twitter With {.oauth = oauth} ', .User = CurrUser}

                    If UI.Page.GetValue("oauth_token") <> "" And UI.Page.GetValue("oauth_verifier") <> "" Then
                        tw.AddLogin(Request("oauth_token"), UI.Page.GetValue("oauth_verifier"))
                        Me.AddJScript("window.close();")
                    Else
                        Response.Redirect(tw.RedirectAuth())
                    End If


                Case WebApi.Type.BUFFER

                    Dim oauth2 = New WebApi.Oauth.Oauth2(MyApp.Network.AccType.BUFFER) With {
                        .client_secret = "5bf0e22c5a9bced4b38ebbba1e6ebbd4",
                        .client_id = "53cce2c1d827aca50c278dba",
                        .redirect_uri = UrlRedir
                    }

                    Dim tw = New MyApp.Network.Buffer With {.oauth2 = oauth2} ', .User = CurrUser}

                    If UI.Page.GetValue("code") <> "" Then
                        tw.AddLogin(UI.Page.GetValue("code"))
                        Me.AddJScript("window.close();")
                    Else
                        Response.Redirect(tw.RedirectAuth())
                    End If



                Case WebApi.Type.FACEBOOK

                    Dim oauth2 = New WebApi.Oauth.Oauth2(MyApp.Network.AccType.FACEBOOK_USER) With {
                        .client_secret = "6e875485e54fa223939de7963d99410b",
                        .client_id = "480442221989699",
                        .redirect_uri = UrlRedir
                    }

                    Dim tw = New MyApp.Network.Facebook With {.oauth2 = oauth2} ', .User = CurrUser}

                    If UI.Page.GetValue("access_token") <> "" Or UI.Page.GetValue("code") <> "" Then
                        tw.AddLogin(UI.Page.GetValue("code"), UI.Page.GetValue("access_token"))
                        Me.AddJScript("window.close();")
                    Else
                        Response.Redirect(tw.RedirectAuth())
                    End If

                Case WebApi.Type.GOOGLE

                    Dim oauth2 = New WebApi.Oauth.Oauth2(MyApp.Network.AccType.GOOGLE_PEOPLE) With {
                        .client_secret = "kpSTKZs2IAKtq3ZohQ8gQBaP",
                        .client_id = "958624268903.apps.googleusercontent.com",
                        .redirect_uri = UrlRedir
                    }

                    Dim tw = New MyApp.Network.Google With {.oauth2 = oauth2} ', .User = CurrUser}

                    If UI.Page.GetValue("access_token") <> "" Or UI.Page.GetValue("code") <> "" Then
                        tw.AddLogin(UI.Page.GetValue("code"))
                        Me.AddJScript("window.close();")
                    Else
                        Response.Redirect(tw.RedirectAuth())
                    End If



                Case WebApi.Type.LINKEDIN

                    Dim oauth2 = New WebApi.Oauth.Oauth2(MyApp.Network.AccType.LINKEDIN_PEOPLE) With {
                        .client_secret = "MDpTWhrdrYBFJ7wO",
                        .client_id = "hrqjjc29hsth",
                        .redirect_uri = UrlRedir
                    }

                    Dim tw = New MyApp.Network.Linkedin With {.oauth2 = oauth2} ', .User = CurrUser}

                    If UI.Page.GetValue("access_token") <> "" Or UI.Page.GetValue("code") <> "" Then
                        tw.AddLogin(UI.Page.GetValue("code"), UI.Page.GetValue("access_token"))
                        Me.AddJScript("window.close();")
                    Else
                        Response.Redirect(tw.RedirectAuth())
                    End If

                Case WebApi.Type.INSTAGRAM

                    Dim oauth2 = New WebApi.Oauth.Oauth2(MyApp.Network.AccType.INSTAGRAM_ACCOUNT) With {
                        .client_secret = "815401d7f20f458885ca624d16876b41",
                        .client_id = "05edfe20b92c4e7c86a73996e7675c67",
                        .redirect_uri = UrlRedir
                    }

                    Dim tw = New MyApp.Network.Instagram With {.oauth2 = oauth2} ', .User = CurrUser}

                    If UI.Page.GetValue("access_token") <> "" Or UI.Page.GetValue("code") <> "" Then
                        tw.AddLogin(UI.Page.GetValue("code"), UI.Page.GetValue("access_token"))
                        Me.AddJScript("window.close();")
                    Else
                        Response.Redirect(tw.RedirectAuth())
                    End If


            End Select


        End If

    End Sub

#End Region



    'Protected Sub BtnPayPal_Click(sender As Object, e As EventArgs) Handles BtnPayPal.Click



    'End Sub

    'Protected Sub BtnPayPalConfirm_Click(sender As Object, e As EventArgs) Handles BtnPayPalConfirm.Click

    '    Dim Uri As New UriBuilder("https://api-3t.sandbox.paypal.com/nvp")

    '    Dim queryString = HttpUtility.ParseQueryString("")

    '    queryString.Add("USER", "evolvo.net-facilitator_api1.gmail.com")
    '    queryString.Add("PWD", "1391768464")
    '    queryString.Add("SIGNATURE", "A2qv3pr765jIRYPhGsApwatsI0jTA.Ae-WRnVV3h7TRIcux9M09ARmA3")
    '    queryString.Add("VERSION", "93")
    '    queryString.Add("METHOD", "GetExpressCheckoutDetails")
    '    queryString.Add("TOKEN", Request("token"))

    '    Uri.Query = queryString.ToString '& "&q=" & webClient.UrlEncode(q)

    '    Dim ww As New Net.WebClient
    '    Dim Res = ww.DownloadString(Uri.Uri.AbsoluteUri)


    '    Dim rerq = HttpUtility.ParseQueryString(Res)



    '    queryString = HttpUtility.ParseQueryString("")

    '    queryString.Add("USER", "evolvo.net-facilitator_api1.gmail.com")
    '    queryString.Add("PWD", "1391768464")
    '    queryString.Add("SIGNATURE", "A2qv3pr765jIRYPhGsApwatsI0jTA.Ae-WRnVV3h7TRIcux9M09ARmA3")
    '    queryString.Add("VERSION", "93")
    '    queryString.Add("METHOD", "DoExpressCheckoutPayment")


    '    queryString.Add("TOKEN", rerq("token"))
    '    queryString.Add("PAYERID", rerq("payerID"))

    '    queryString.Add("PAYMENTREQUEST_0_PAYMENTACTION", "SALE")
    '    queryString.Add("PAYMENTREQUEST_0_AMT", "10")
    '    queryString.Add("PAYMENTREQUEST_0_CURRENCYCODE", "USD")
    '    queryString.Add("PAYMENTREQUEST_0_DESC", "Abbonamento mensile")

    '    Uri.Query = queryString.ToString '& "&q=" & webClient.UrlEncode(q)

    '    Res = ww.DownloadString(Uri.Uri.AbsoluteUri)


    '    rerq = HttpUtility.ParseQueryString(Res)


    'End Sub




    Protected Sub SetDataSubscription()
        'Me.Items("Plan_Id") = CurrU ser.Plan_Id
        Me.BtnAddAccount.Visible = CurrUser.Email_Confirm

    End Sub


End Class
